<?php

namespace app\common\model\hfztcy;

use app\common\model\BaseModel;
use app\common\model\service\LibUploadCompressImage;
use common\Common;
use think\Db;
use think\Exception;
use think\Validate;

//公共函数

/**
 * 门店列表
 * @name LibStore.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibStore extends BaseModel
{
    protected $model;
    protected $table = 'hfztcy_store';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = db($this->table);
        parent::__construct();
    }

    /**
     * 添加表单信息
     */
    public function addStore($condition)
    {
        try {
            $result = $this->model->insertGetId($condition);
            if (true == $result) {
                return Common::errorArray(0, "添加成功", $result);
            } else {
                return Common::errorArray(1, "添加失败", $result);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }


    /**
     * 查询单个表单信息
     * @param $condition
     * @param array $result
     */
    public function findStore($condition = '', $field = '')
    {
        try {
            $reslut = $this->model->where($condition)->field($field)->find();

            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 查询多个表单信息
     * @param $condition
     * @param $limit
     * @param $field
     * @param $sort
     * @param array $result
     */
    public function findAllStore($condition = '', $limit = '', $field = '', $sort = 'id desc')
    {
        try {
            $reslut = $this->model->where($condition)->order($sort)->limit($limit)->field($field)->select();
            if (true == $reslut) {
                return Common::errorArray(0, "查询成功", $reslut);
            } else {
                return Common::errorArray(1, "查询为空", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 更新表单信息
     * @param $condition
     * @param $userInfo
     * @param array $result
     */
    public function updateStore($condition, $userInfo)
    {
        try {
            $reslut = $this->model->where($condition)->update($userInfo);
            if ($reslut >= 0) {
                return Common::errorArray(0, "更新成功", $reslut);
            } else {
                return Common::errorArray(1, "更新失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 删除表单信息
     * @param $condition
     * @param array $result
     */
    public function deleteStore($ids)
    {
        $condition = array('id' => array('in', $ids));
        try {
            $reslut = $this->model->where($condition)->delete();;
            if (true == $reslut) {
                return Common::errorArray(0, "删除成功", $reslut);
            } else {
                return Common::errorArray(1, "删除失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值加1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function increaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setInc($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * 字段值减1
     * @param $condition
     * @param string $field
     * @param int $optval
     * @param array $reslut
     */
    public function decreaseField($condition, $field, $optval = 1)
    {
        try {
            $reslut = $this->model->where($condition)->setDec($field, $optval);;
            if (true == $reslut) {
                return Common::errorArray(0, "修改成功", $reslut);
            } else {
                return Common::errorArray(1, "修改失败", $reslut);
            }
        } catch (Exception $ex) {
            $this->errorLog(__CLASS__, __FUNCTION__, $ex);
            return Common::errorArray(1, "数据库操作失败".$ex->getMessage(), $ex);
        }
    }

    /**
     * Info: 上传图片
     * Date: 2022/6/17 9:45
     */
    public function uploadStorePhoto()
    {
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/目录下
        if ($file) {
            $dir = "upload/store/photos/";
            $moveImage = $file->move(ROOT_PATH . 'public' . DS . $dir);
            if ($moveImage) {
                $name = $moveImage->getSaveName();
                $name = str_replace("\\", "/", $name);
                $new_path = $dir . $name;
                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
            } else {
                // 上传失败获取错误信息
                return Common::errorArray(1, "上传失败", $file->getError());
            }
        } else {
            return Common::errorArray(2, "没有上传", false);
        }
    }

    /**
     * Info: 上传视频
     * Date: 2022/6/17 9:45
     */
    public function uploadStoreVcr()
    {
        $file = request()->file('vcr');
        if ($file) {
            $dir = "upload/store/video/";
            $moveImage = $file->move(ROOT_PATH . 'public' . DS . $dir);
            if ($moveImage) {
                $name = $moveImage->getSaveName();
                $name = str_replace("\\", "/", $name);
                $new_path = $dir . $name;
                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
            } else {
                // 上传失败获取错误信息
                return Common::errorArray(1, "上传失败", $file->getError());
            }
        } else {
            return Common::errorArray(2, "没有上传", false);
        }
    }

    /**
     * Info: 上传视频封面
     * Date: 2022/6/17 9:45
     */
    public function uploadStoreImgs()
    {
        $res = (new LibUploadCompressImage('store/store_imgs','storeimgs'))->uploadImage();
        if ($res['errorCode'] == 0) {
            return Common::errorArray(0, "上传成功", ['path' => $res['data']]);
        }
        return $res;
    }

    /**
     * Info: 上传视频封面
     * Date: 2022/6/17 9:45
     */
    public function uploadStoreVcrImgs()
    {
//        $file = request()->file('imgs');
//        if ($file) {
//            $dir = "upload/store/video_cover/";
//            $moveImage = $file->move(ROOT_PATH . 'public' . DS . $dir);
//            if ($moveImage) {
//                $name = $moveImage->getSaveName();
//                $name = str_replace("\\", "/", $name);
//                $new_path = $dir . $name;
//                return Common::errorArray(0, "上传成功", ['path' => $new_path]);
//            } else {
//                // 上传失败获取错误信息
//                return Common::errorArray(1, "上传失败", $file->getError());
//            }
//        } else {
//            return Common::errorArray(2, "没有上传", false);
//        }
        $res = (new LibUploadCompressImage('store/video_cover','imgs'))->uploadImage();
        if ($res['errorCode'] == 0) {
            return Common::errorArray(0, "上传成功", ['path' => $res['data']]);
        }
        return $res;
    }

    /**
     * 分页获取数据表单信息
     */
    public function pagingStore($page, $whereStr)
    {
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;

        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

    $querySQL = <<< SQL
SELECT *
FROM (
    SELECT x.*,z.username memberUsername,y.identity
    FROM {$this->table} AS x
        LEFT JOIN `hfztcy_user` AS z ON x.uid = z.user_id
    	LEFT JOIN `base_user` AS y ON x.uid = y.id) AS a
WHERE {$where}
ORDER BY id DESC
SQL;
        $sql = $querySQL . " LIMIT {$m}, {$n}";
        //echo $sql;die();
        $sqlAll = $querySQL;

        $result ['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';
        return $result;
    }

    /**
     * 分页获取数据表单信息
     */
    public function pagingStoreList($page, $whereStr,$lat,$lng)
    {
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;

        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

    $querySQL = <<< SQL
SELECT *
FROM (
    SELECT x.*,(
            ROUND(6378.138*2* ASIN(
                SQRT(POW(SIN(({$lat}*pi()/180-lat*pi()/180)/2),2)+
                    COS({$lat}*pi()/180)*
                    COS(lat*pi()/180)*
                    POW(SIN(({$lng}*pi()/180-lng*pi()/180)/2),2))
                )*1000)
        ) AS distance
    FROM {$this->table} AS x
    ) AS a
WHERE {$where}
ORDER BY distance ASC
SQL;
//        $querySQL = <<< SQL
//SELECT *
//FROM  {$this->table} AS a
//WHERE {$where}
//ORDER BY id ASC
//SQL;
        $sql = $querySQL . " LIMIT {$m}, {$n}";
        //echo $sql;die();
        $sqlAll = $querySQL;

        $result ['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';
        return $result;
    }

    /**
     * 分页获取数据表单信息
     */
    public function pagingStoreListByApi($page, $whereStr,$lat,$lng)
    {
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;

        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $where = 'id IS NOT NULL';
        if ($whereStr) {
            $where = "{$whereStr}";
        }

    $querySQL = <<< SQL
SELECT *
FROM (
    SELECT x.*,(
            ROUND(6378.138*2* ASIN(
                SQRT(POW(SIN(({$lat}*pi()/180-lat*pi()/180)/2),2)+
                    COS({$lat}*pi()/180)*
                    COS(lat*pi()/180)*
                    POW(SIN(({$lng}*pi()/180-lng*pi()/180)/2),2))
                )*1000)
        ) AS distance
    FROM {$this->table} AS x
    ) AS a
WHERE {$where}
ORDER BY distance ASC
SQL;
//        $querySQL = <<< SQL
//SELECT *
//FROM  {$this->table} AS a
//WHERE {$where}
//ORDER BY id ASC
//SQL;
        $sql = $querySQL . " LIMIT {$m}, {$n}";
        //echo $sql;die();
        $sqlAll = $querySQL;

        $result ['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';
        return $result;
    }

    /**
     * Info: 数据验证
     * Date: 2022/6/17 9:55
     */
    public function goCheck($data, $opt = 'add')
    {
        $rule = [
            'id' => 'require',
            'title' => 'require',
            'city' => 'require',
            'address' => 'require',
            'username' => 'require',
            'password' => 'require',
        ];

        $msg = [
            'id.require' => 'ID不能为空',
            'title.require' => '标题不能为空',
            'city.require' => '城市不能为空',
            'address.require' => '地址不能为空',
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空',
        ];

        $scene = [
            'add' => ['title', 'city', 'address'],
            'edit' => ['id', 'title', 'city', 'address'],
            'del' => ['id'],
            'login' => ['username','password'],
        ];

        $validate = new Validate($rule, $msg);
        $validate->scene($opt, $scene[$opt]);
        if (!$validate->scene($opt)->check($data)) {
            return Common::errorArray(1, $validate->getError(), false);
        }
        return Common::errorArray(0, '验证通过', true);
    }
}

?>